<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="任务名称" prop="dhpTaskName">
                <el-input v-model="queryParams.dhpTaskName" placeholder="请输入任务名称" clearable />
            </el-form-item>
            <el-form-item label="震级" prop="dhpMagnitude">
                <!-- <el-select v-model="queryParams.dhpMagnitude" placeholder="请输入震级" clearable>
                    <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select> -->
                <el-input v-model="queryParams.dhpMagnitude" placeholder="请输入震级" clearable />
            </el-form-item>
            <el-form-item label="年份" prop="dhpYear">
                <el-date-picker v-model="queryParams.dhpYear" type="year" placeholder="请选择年份" value-format="YYYY" clearable />
            </el-form-item>
            <el-form-item label="宏观位置" prop="dhpLocation">
                <el-input v-model="queryParams.dhpLocation" placeholder="请输入宏观位置" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">添加</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button plain icon="Download" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Edit" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5" v-if="isAdmin">
                <el-button plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" ref="tabledRef" row-key="id">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
            <el-table-column label="任务名称" align="center" prop="dhpTaskName" width="240px" show-overflow-tooltip>
                <template #default="scope">
                    <span @click="detailDed(scope.row)" style="color: var(--el-color-primary);cursor: pointer;">{{scope.row.dhpTaskName
                    }}</span></template>
            </el-table-column>
            <el-table-column label="设定地震序号" align="center" prop="dhpEarthquakeNum" />
            <el-table-column label="经度" align="center" prop="dhpEpicenterLongitude" />
            <el-table-column label="纬度" align="center" prop="dhpEpicenterLatitude" />
            <el-table-column label="年份" align="center" prop="dhpYear" />
            <el-table-column label="宏观位置" align="center" prop="dhpLocation" width="240px" show-overflow-tooltip/>
            <el-table-column label="震级" align="center" prop="dhpMagnitude" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isAdmin">
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 查看弹出框 -->
        <el-dialog v-model="openDetail" :title="title" width="1200px" append-to-body>
            <p class="dialogTitle">{{title}}</p>
            <el-form ref="historyAssessDataRef" :model="form" :rules="rules">
            <h3><span></span> 设定地震基本信息</h3>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="任务名称" prop="dhpTaskName"  label-width="110px">
                        <el-input v-model="form.dhpTaskName" placeholder="请输入任务名称" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="4"></el-col> 
                <el-col :span="12">
                    <el-form-item label="任务编号" prop="dhpTaskNum"  label-width="110px" >{{form.dhpTaskNum}}</el-form-item></el-col>       
                <el-col :span="8">
                    <el-form-item label="经度" prop="dhpEpicenterLongitude" label-width="110px">
                        <el-input v-model="form.dhpEpicenterLongitude" placeholder="请输入经度" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="纬度" prop="dhpEpicenterLatitude" label-width="110px">
                        <el-input v-model="form.dhpEpicenterLatitude" placeholder="请输入纬度" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="设定地震序号" prop="dhpEarthquakeNum" label-width="110px">
                        <el-input v-model="form.dhpEarthquakeNum" placeholder="请输入设定地震序号" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="年份" prop="dhpYear" label-width="110px">
                        <el-date-picker v-model="form.dhpYear" type="year" placeholder="请选择年份" value-format="YYYY" clearable :disabled="true" style="width:100%" />
                    </el-form-item>
                </el-col>  
                <el-col :span="8">
                    <el-form-item label="震级" prop="dhpMagnitude" label-width="110px">
                        <el-input v-model="form.dhpMagnitude" placeholder="请输入震级" :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="宏观位置" prop="dhpLocation" label-width="110px">
                        <el-input v-model="form.dhpLocation" placeholder="请输入宏观位置" :disabled="true"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <h3><span></span> 预评估结果</h3>
            <table class="tableDialog">
                <tr class="tableHead">
                    <td>受灾区域面积<br/>（平方公里）</td>
                    <td>灾区总人数<br/>（万人）</td>
                    <td>灾区范围内GDP<br/>（亿）</td>
                    <td>死亡人数<br/>（人）</td>
                    <td>受伤人数<br/>（人）</td>
                    <td>灾区经济损失<br/>（亿元）</td>
                    <td>需紧急安置人数<br/>（人）</td>
                </tr>
                <tr>
                    <td>
                        <el-form-item prop="dhpDiArea">
                            <el-input v-model="form.dhpDiArea" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpDiPeople">
                            <el-input v-model="form.dhpDiPeople" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpDiGdp">
                            <el-input v-model="form.dhpDiGdp" :disabled="!isEdit"/>
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsDeath">
                            <el-input v-model="form.dhpEsDeath" :disabled="!isEdit"/>
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsInjured">
                            <el-input v-model="form.dhpEsInjured" :disabled="!isEdit"/>
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpDiEcLosses">
                            <el-input v-model="form.dhpDiEcLosses" :disabled="!isEdit"/>
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsResNumber">
                            <el-input v-model="form.dhpEsResNumber" :disabled="!isEdit"/>
                        </el-form-item>
                    </td>
                </tr>
            </table>
            <table class="tableDialog">
                <tr class="tableHead">
                    <td colspan="4">需紧急救援力量</td>
                </tr>
                <tr class="tableHead">
                    <td>总计（人）</td>
                    <td>其中专业救援力量（人）</td>
                    <td>其中民间救援力量（人）</td>
                    <td>其中社会其他救援力量</td>
                </tr>
                <tr>
                    <td>
                        <el-form-item prop="dhpNeedEmeAssi">
                            <el-input v-model="form.dhpNeedEmeAssi" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpProResForce">
                            <el-input v-model="form.dhpProResForce" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpCivRelEfforts">
                            <el-input v-model="form.dhpCivRelEfforts" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpOtherForces">
                            <el-input v-model="form.dhpOtherForces" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                </tr>
            </table>
            <table class="tableDialog">
                <tr class="tableHead">
                    <td>需帐篷数<br/>（顶）</td>
                    <td>需担架<br/>（付）</td>
                    <td>需棉被<br/>（床）</td>
                    <td>需食品<br/>（吨）</td>
                    <td>需饮水<br/>（吨）</td>
                    <td>需临时厕所<br/>（个）</td>
                    <td>需临时浴室<br/>（个）</td>
                </tr>
                <tr>
                    <td>
                        <el-form-item prop="dhpEsTentsNum">
                            <el-input v-model="form.dhpEsTentsNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsStretcherNum">
                            <el-input v-model="form.dhpEsStretcherNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsQuiltNum">
                            <el-input v-model="form.dhpEsQuiltNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsFoodNum">
                            <el-input v-model="form.dhpEsFoodNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsWaterNum">
                            <el-input v-model="form.dhpEsWaterNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsToiletNum">
                            <el-input v-model="form.dhpEsToiletNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsBathroomNum">
                            <el-input v-model="form.dhpEsBathroomNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                </tr>
            </table>
            <table class="tableDialog">
                <tr class="tableHead">
                    <td colspan="4">需医务人员</td>
                    <td rowspan="2">需病房<br/>（平方米）</td>
                    <td rowspan="2">需病床<br/>（张）</td>
                    <td rowspan="2">需血浆<br/>（升）</td>
                </tr>
                <tr class="tableHead">
                    <td>总计<br/>（人）</td>
                    <td>其中医生<br/>（人）</td>
                    <td>其中护士<br/>（人）</td>
                    <td>其中心理医生<br/>（人）</td>
                </tr>
                <tr>
                    <td>
                        <el-form-item prop="dhpEsStaffNum">
                            <el-input v-model="form.dhpEsStaffNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsWardNum">
                            <el-input v-model="form.dhpEsWardNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsBedNum">
                            <el-input v-model="form.dhpEsBedNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsStaffNum">
                            <el-input v-model="form.dhpEsStaffNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsDoctorNum">
                            <el-input v-model="form.dhpEsDoctorNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsNurseNum">
                            <el-input v-model="form.dhpEsNurseNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                    <td>
                        <el-form-item prop="dhpEsPsyDoctorNum">
                            <el-input v-model="form.dhpEsPsyDoctorNum" :disabled="!isEdit" />
                        </el-form-item>
                    </td>
                </tr>
            </table>
            <h3><span></span> 对策建议</h3>
            <table class="tableDialog">
                <tr class="tableHead">
                    <td>灾害情景分析</td>
                    <td>年度风险应对策略</td>
                    <td>应急备灾对策</td>
                    <td>应急处置对策</td>                    
                </tr>
                <tr style="height:35px">
                    <td>
                        <el-button type="text" @click="viewDisaster" v-if="task!=''||task">查看</el-button>
                    </td>
                    <td>
                        <el-button type="text" @click="viewAgel" v-if="task!=''||task">查看</el-button>
                    </td>
                    <td>
                        <el-button type="text"  @click="viewEmergencyDisaster" v-if="task!=''||task">查看</el-button>
                    </td>
                    <td>
                        <el-button type="text" @click="viewEmergencyDisposal" v-if="task!=''||task">查看</el-button>
                    </td>                    
                </tr>
            </table>
            <h3><span></span> 预评估报告</h3>
            <div class="preEvaReport">
                <el-row>
                    <el-col :span="6" class="evaTitle">
                        简本报告
                    </el-col>
                    <el-col :span="18">
                       <el-button type="text" @click="downloadReport(form.id,1)" v-if="report">{{report.userUploadSimpleReportName}}</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="evaTitle">
                        简本报告上传人
                    </el-col>
                    <el-col :span="6">
                        <span v-if="report">{{report.simpleReportUploadUserName}}</span>
                    </el-col>
                    <el-col :span="6" class="evaTitle">
                        简本报告上传日期
                    </el-col>
                    <el-col :span="6">
                        <span v-if="report">{{report.simpleReportUploadTime}}</span>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="evaTitle">
                        详本报告
                    </el-col>
                    <el-col :span="18">
                        <el-button type="text" @click="downloadReport(form.id,2)" v-if="report">{{report.userUploadMinuteReportName}}</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="evaTitle">
                        详本报告上传人
                    </el-col>
                    <el-col :span="6">
                        <span v-if="report">{{report.minuteReportUploadUserName}}</span>
                    </el-col>
                    <el-col :span="6" class="evaTitle">
                        详本报告上传日期
                    </el-col>
                    <el-col :span="6">
                        <span v-if="report">{{report.minuteReportUploadTime}}</span>
                    </el-col>
                </el-row>
            </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForms" v-if="isEdit">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError"
                :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            @click="importTemplate('历史预评估数据模板.xlsx')">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button plain @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!--查看 灾害情景分析弹出框 -->
        <el-dialog v-model="openDisasterScenarios" append-to-body>
            <p class="dialogTitle">灾害情景分析</p>
            <DisasterScenarios ref="disasters" :form="task" @changeAreaList="changeAreaList" @getAreaList="getAreaList" :isDisabled="!isDisabled" v-if="openDisasterScenarios"/>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm"  v-if="isDisabled">确定</el-button>
                    <el-button plain @click="cancelDisasterScenarios">关闭</el-button>
                </div>
            </template>
        </el-dialog>
        <!--查看 年度风险应对策略建议弹出框 -->
        <el-dialog v-model="openAgel" append-to-body>
            <p class="dialogTitle">年度风险应对策略建议</p>
            <Agel ref="agels" :form="task"  @changeAreaList1="changeAreaList1" @getAreaList1="getAreaList1" :isDisabled="!isDisabled" v-if="openAgel"/>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm1" v-if="isDisabled">确定</el-button>
                    <el-button plain @click="cancelAgel">关闭</el-button>
                </div>
            </template>
        </el-dialog>
        <!--查看 应急备灾对策弹出框 -->
        <el-dialog v-model="openEmergencyDisaster" append-to-body>
            <p class="dialogTitle">应急备灾对策</p>
            <EmergencyDisaster ref="emergencyDisasters" :form="task" @changeAreaList2="changeAreaList2" @getAreaList2="getAreaList2" :isDisabled="!isDisabled" v-if="openEmergencyDisaster"/>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm2" v-if="isDisabled">确定</el-button>
                    <el-button plain @click="cancelEmergencyDisaster">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!--查看 应急处置对策弹出框 -->
        <el-dialog v-model="openEmergencyDisposal" append-to-body>
            <p class="dialogTitle">应急处置对策</p>
            <EmergencyDisposal ref="emergencyDisposals" :form="task" @changeAreaList3="changeAreaList3" @getAreaList3="getAreaList3" :isDisabled="!isDisabled" v-if="openEmergencyDisposal"/>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm3" v-if="isDisabled">确定</el-button>
                    <el-button plain @click="cancelEmergencyDisposal">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="historyAssessData">
import { positive2decimals, positive1decimals, positiveInteger } from "@/utils/history.js"
import { getToken } from "@/utils/auth";
import { listDifference, updateDifference, delDifference, getDifference, getRole } from "@/api/basedatamanage/historyAssessData.js"
import DisasterScenarios from "./disasterScenarios.vue";
import Agel from "./agel.vue";
import EmergencyDisaster from "./emergencyDisaster.vue";
import EmergencyDisposal from "./emergencyDisposal.vue";
import { getArea } from "@/api/suggestions/analyse.js";
import { getUserId } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

import { saveDisasterScenario,saveAnnualRisk,saveEmergencyDisaster,saveEmergencyDisposal} from "@/api/suggestions/analyse.js";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const openDetail = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isEdit = ref(false);
const showSearch = ref(true);
const isAdmin = ref(true);
const num = ref(undefined)
const openDisasterScenarios = ref(false)
const openAgel = ref(false)
const openEmergencyDisaster  = ref(false)
const openEmergencyDisposal  = ref(false)
/*** 导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/baseData/hisPr/importExcel"
});

const numberQJ = (rule, value, callback) => {
    // if (!value) {
    //     return callback(new Error());
    //   }else if (value.length!=2) {
    //     return callback(new Error());
    //   }else if (value[0]>=value[1]) {
    //     return callback(new Error());
    //   }else{
    //     callback();
    //   }
}
const data = reactive({
    form: {
        dhpTaskName: undefined,
        dhpYear: undefined,
        dhpEpicenterLongitude: undefined,
        dhpEpicenterLatitude: undefined,
        dhpEarthquakeNum: undefined,
        dhpLocation: undefined,
        dhpMagnitude: undefined,
        dhpDiArea: undefined,
        dhpDiPeople: undefined,
        dhpDiGdp: undefined,
        dhpDiEcLosses: undefined,
        dhpEsDeath: undefined,
        dhpEsInjured: undefined,
        dhpEsResNumber: undefined,
        dhpNeedEmeAssi: undefined,
        dhpProResForce: undefined,
        dhpCivRelEfforts: undefined,
        dhpOtherForces: undefined,
        dhpEsTentsNum: undefined,
        dhpEsStretcherNum: undefined,
    },
    queryParams: {
        page: 1,
        rows: 10,
        dhpTaskName: undefined,
        dhpMagnitude: undefined,
        dhpYear: undefined,
        dhpLocation: undefined,
    },
    rules: {
        dhpTaskName: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
        dhpEpicenterLongitude: [{ required: true, message: '请输入正确的值，保留两位小数', trigger: 'blur', validator: positive2decimals }],
        dhpEpicenterLatitude: [{ required: true, message: '请输入正确的值，保留两位小数', trigger: 'blur', validator: positive2decimals }],
        dhpEarthquakeNum: [{ required: true, message: "地震序号不能为空", trigger: "blur" }],
        dhpYear: [{ required: true, message: "年份不能为空", trigger: 'change' }],
        dhpLocation: [{ required: true, message: "宏观位置不能为空", trigger: "blur" }],
        dhpMagnitude: [{ required: true, message: '请输入正确的值，保留一位小数', trigger: 'blur', validator: positive1decimals }],
        dhpDiArea: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        dhpDiPeople: [{ required: true, message: '总人数不能为空', trigger: 'blur' }],
        dhpDiGdp: [{ required: true, message: 'GDP不能为空', trigger: 'blur'}],
        dhpEsDeath: [{ required: true, message: '死亡人数不能为空', trigger: 'blur' }],
        dhpEsInjured: [{ required: true, message: '受伤人数不能为空', trigger: 'blur' }],
        dhpDiEcLosses: [{ required: true, message: '经济损失不能为空', trigger: 'blur' }],
        dhpEsResNumber: [{ required: true, message: '安置人数不能为空', trigger: 'blur' }],
        dhpNeedEmeAssi: [{ required: true, message: '总计不能为空', trigger: 'blur' }],
        dhpProResForce: [{ required: true, message: '专业救援力量不能为空', trigger: 'blur' }],
        dhpCivRelEfforts: [{ required: true, message: '民间救援力量不能为空', trigger: 'blur' }],
        dhpOtherForces: [{ required: true, message: '社会救援力量不能为空', trigger: 'blur' }],
        dhpEsTentsNum: [{ required: true, message: '需帐篷数不能为空', trigger: 'blur' }],
        // dhpEsStretcherNum: [{ required: false, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsQuiltNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsFoodNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsWaterNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsToiletNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsBathroomNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsStaffNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsWardNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsBedNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsStaffNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsDoctorNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsNurseNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
        // dhpEsPsyDoctorNum: [{ required: true, message: '请输入正确的区间', trigger: 'blur',validator: numberQJ }],
    },
    task:'',
    // 灾害情景分析
    disasterScenariosData: [],
    // 年度风险应对策略
    agelData: [],
    // 应急备灾对策
    emergencyDisasterData: [],
    // 应急处置对策
    emergencyDisposalData: [],
    report: {},
    taskName: ''
})
const { queryParams, form, rules,taskName,task, disasterScenariosData, agelData, emergencyDisasterData, emergencyDisposalData, report } = toRefs(data)
/** 搜索按钮操作 */
function handleQuery() {
    console.log(queryParams.value.dhpYear);
    queryParams.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}

// 重置表单
function reset() {
    form.value = {
        dhpTaskName: undefined,
        dhpYear: undefined,
        dhpEpicenterLongitude: undefined,
        dhpEpicenterLatitude: undefined,
        dhpEarthquakeNum: undefined,
        dhpLocation: undefined,
        dhpMagnitude: undefined,
        dhpDiArea: undefined,
        dhpDiPeople: undefined,
        dhpDiGdp: undefined,
        dhpDiEcLosses: undefined,
        dhpEsDeath: undefined,
        dhpEsInjured: undefined,
        dhpEsResNumber: undefined,
        dhpNeedEmeAssi: undefined,
        dhpProResForce: undefined,
        dhpCivRelEfforts: undefined,
        dhpOtherForces: undefined,
        dhpEsTentsNum: undefined,
        dhpEsStretcherNum: undefined,
    }
    proxy.resetForm("historyAssessDataRef");
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 查询历史预评估数据列表 */
function getList() {
    loading.value = true;
    listDifference(queryParams.value).then(response => {
        dataList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const id = row.id || ids.value;
    console.log(id,'删除下标');
    proxy.$modal.confirm('是否确认删除勾选的历史预评估数据？').then(function () {
        return delDifference(id);
    }).then((res) => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
    }).catch(() => { });
}

// 修改
function handleUpdate(row) {
    reset();
    isEdit.value = true;
    getDetail(row.id)
}
// 预评估详情
function getDetail(id) {
    getDifference(id).then(res => {
        form.value = res.data.hisPr;
        taskName.value = res.data.hisPr.dhpTaskName
        task.value = res.data.task;
        disasterScenariosData.value = []
        agelData.value = []
        emergencyDisasterData.value = []
        emergencyDisposalData.value = []
        report.value = res.data.report
        if (isEdit.value) {
            openDetail.value = true;
            title.value = "修改历史预评估数据"
        } else {
            openDetail.value = true;
            title.value = "查看历史预评估数据"
        }
    })
}
/** 查看方法*/
function detailDed(row) {
    reset();
    isEdit.value = false;
    openDetail.value = true;
    getDetail(row.id)
}
// 获取 区县或者地市
function getAreaData(query) {
    getArea(query).then(response => {
        if (query.suggestionName == '灾害情景分析') {
            task.value.areaList = response.data['灾害情景分析'];
            openDisasterScenarios.value = true;
        } else if (query.suggestionName == '年度风险应对策略建议') {
            task.value.areaList = response.data['年度风险应对策略建议'];
            openAgel.value = true
        } else if (query.suggestionName == '应急备灾对策') {
            task.value.areaList = response.data['应急备灾对策'];
            openEmergencyDisaster.value = true
        } else if (query.suggestionName == '应急处置对策') {
            task.value.areaList = response.data['应急处置对策'];
            openEmergencyDisposal.value = true
        }
    })
}
// 对策建议-灾害情景分析
const isDisabled = ref(false);
function viewDisaster() {
    if(title.value == "查看历史预评估数据"){
        isDisabled.value = false;
    }else{
        isDisabled.value = true;
    }
    const query = {
        flag: 0,
        taskDistrict: task.value.taskDistrict,
        suggestionName: '灾害情景分析',
        taskNum: task.value.taskNum,
    }
    getAreaData(query);
}
function cancelDisasterScenarios(){
    openDisasterScenarios.value = false
}
function changeAreaList(value){
    task.value.areaList = value;
}
function getAreaList(value){
    task.value.areaList = value;
}
// 对策建议-年度风险应对策略
function viewAgel(){
    if(title.value == "查看历史预评估数据"){
        isDisabled.value = false;
    }else{
        isDisabled.value = true;
    }
    const query = {
        flag: 0,
        taskDistrict: task.value.taskDistrict,
        suggestionName: '年度风险应对策略建议',
        taskNum: task.value.taskNum,
    }
    getAreaData(query);
}
function cancelAgel(){
    openAgel.value = false
}
function changeAreaList1(value){
    task.value.areaList = value;
}
function getAreaList1(value){
    task.value.areaList = value;
}
// 对策建议-应急备灾对策
function viewEmergencyDisaster(){
    if(title.value == "查看历史预评估数据"){
        isDisabled.value = false;
    }else{
        isDisabled.value = true;
    }
    const query = {
        flag: 0,
        taskDistrict: task.value.taskDistrict,
        suggestionName: '应急备灾对策',
        taskNum: task.value.taskNum,
    }
    getAreaData(query);
}
function cancelEmergencyDisaster(){
    openEmergencyDisaster.value = false
}
function changeAreaList2(value){
    task.value.areaList = value;
}
function getAreaList2(value){
    task.value.areaList = value;
}
// 对策建议-应急处置对策
function viewEmergencyDisposal(){
    if(title.value == "查看历史预评估数据"){
        isDisabled.value = false;
    }else{
        isDisabled.value = true;
    }
    const query = {
        flag: 0,
        taskDistrict: task.value.taskDistrict,
        suggestionName: '应急处置对策',
        taskNum: task.value.taskNum,
    }
    getAreaData(query);
}
function cancelEmergencyDisposal(){
    openEmergencyDisposal.value = false
}
function changeAreaList3(value){
    task.value.areaList = value;
}
function getAreaList3(value){
    task.value.areaList = value;
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['disasters'].getAreaList();
    proxy.$refs['disasters'].getDisasterScenariosRef().validate((valid, obj) => {
        if (!valid) {
            let newObj = {}
            newObj = most(Object.keys(obj))
            if (form.value.areaList[0].area) {
                const messageError = errorMessage(newObj, 'area', 5, 1);                
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveDisasterScenario(task.value.areaList).then(response => {
                        // localStorage.setItem(form.value.id+'灾害情景分析','0')
                        proxy.$modal.msgSuccess("保存成功");
                        openDisasterScenarios.value = false;
                    });
                }
            } else {
                const messageError = errorMessage(newObj, 'city', 5, 1);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveDisasterScenario(task.value.areaList).then(response => {
                        // localStorage.setItem(task.value.id+'灾害情景分析','1')
                        proxy.$modal.msgSuccess("保存成功");
                        openDisasterScenarios.value = false;
                    });
                }
            }
        } else {
            task.value.areaList.forEach(item => {
                item.maintainer = userStore.name;
                item.maintainTime = getNowFormatTime();
                item.taskNum = task.value.taskNum;
                item.maintainerId = getUserId();
                item.divisionFlag = item.area ? '0' : '1';
            })
            saveDisasterScenario(task.value.areaList).then(response => {
                // localStorage.setItem(task.value.id+'灾害情景分析', task.value.areaList[0].area?'0':'1')
                proxy.$modal.msgSuccess("保存成功");
                openDisasterScenarios.value = false;
            });
        }
    });
}

function submitForm1() {
    proxy.$refs['agels'].getAreaList1();
    proxy.$refs['agels'].getAgelRef().validate((valid, obj) => {
        if (!valid) {
            let newObj = {}
            newObj = most(Object.keys(obj))
            if (task.value.areaList[0].area) {
                const messageError = errorMessage(newObj, 'area', 4, 2);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveAnnualRisk(task.value.areaList).then(response => {
                        // localStorage.setItem(form1.value.id+'年度风险应对策略建议','0')
                        proxy.$modal.msgSuccess("保存成功");
                        openAgel.value = false;
                    });
                }
            } else {
                const messageError = errorMessage(newObj, 'city', 4, 2);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveAnnualRisk(task.value.areaList).then(response => {
                        // localStorage.setItem(form1.value.id+'年度风险应对策略建议','1')
                        proxy.$modal.msgSuccess("保存成功");
                        openAgel.value = false;
                    });
                }
            }
        } else {
            task.value.areaList.forEach(item => {
                item.maintainer = userStore.name;
                item.maintainTime = getNowFormatTime();
                item.taskNum = task.value.taskNum;
                item.maintainerId = getUserId();
                item.divisionFlag = item.area ? '0' : '1';
            })
            saveAnnualRisk(task.value.areaList).then(response => {
                // localStorage.setItem(form1.value.id+'年度风险应对策略建议', form1.value.areaList[0].area?'0':'1')
                proxy.$modal.msgSuccess("保存成功");
                openAgel.value = false;
            });
        }
    });
}

function submitForm2() {
    proxy.$refs['emergencyDisasters'].getAreaList2();
    proxy.$refs['emergencyDisasters'].getEmergencyDisasterRef().validate((valid, obj) => {
        if (!valid) {
            let newObj = {}
            newObj = most(Object.keys(obj))
            if (task.value.areaList[0].area) {
                const messageError = errorMessage(newObj, 'area', 8, 3);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveEmergencyDisaster(task.value.areaList).then(response => {
                        // localStorage.setItem(form2.value.id+'应急备灾对策','0')
                        proxy.$modal.msgSuccess("保存成功");
                        openEmergencyDisaster.value = false;
                    });
                }
            } else {
                const messageError = errorMessage(newObj, 'city', 8, 3);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveEmergencyDisaster(task.value.areaList).then(response => {
                        // localStorage.setItem(form2.value.id+'应急备灾对策','1')
                        proxy.$modal.msgSuccess("保存成功");
                        openEmergencyDisaster.value = false;
                    });
                }
            }
        } else {
            task.value.areaList.forEach(item => {
                item.maintainer = task.value.maintainer;
                item.maintainTime = getNowFormatTime();
                item.taskNum = task.value.taskNum;
                item.maintainerId = item.maintainerId ? item.maintainerId : getUserId();
                item.divisionFlag = item.area ? '0' : '1';
            })
            saveEmergencyDisaster(task.value.areaList).then(response => {
                // localStorage.setItem(form2.value.id+'应急备灾对策', form2.value.areaList[0].area?'0':'1')
                proxy.$modal.msgSuccess("保存成功");
                openEmergencyDisaster.value = false;
            });
        }
    });
}

function submitForm3() {
    proxy.$refs['emergencyDisposals'].getAreaList3();
    proxy.$refs['emergencyDisposals'].getEmergencyDisposalRef().validate((valid, obj) => {
        if (!valid) {
            let newObj = {}
            newObj = most(Object.keys(obj))
            if (form3.value.areaList[0].area) {
                const messageError = errorMessage(newObj, 'area', 9, 4);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = getNowFormatTime();
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveEmergencyDisposal(task.value.areaList).then(response => {
                        // localStorage.setItem(form3.value.id+'应急处置对策','0')
                        proxy.$modal.msgSuccess("保存成功");
                        openEmergencyDisposal.value = false;
                    });
                }
            } else {
                const messageError = errorMessage(newObj, 'city', 9, 4);
                if (messageError.length != 0) {
                    const msg = messageError.join('<br/><br/>')
                    ElMessage({
                        message: msg,
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                } else {
                    task.value.areaList.forEach(item => {
                        item.maintainer = userStore.name;
                        item.maintainTime = task.value.maintainTime;
                        item.taskNum = task.value.taskNum;
                        item.maintainerId = getUserId();
                        item.divisionFlag = item.area ? '0' : '1';
                    })
                    saveEmergencyDisposal(task.value.areaList).then(response => {
                        // localStorage.setItem(task.value.id+'应急处置对策','1')
                        proxy.$modal.msgSuccess("保存成功");
                        openEmergencyDisposal.value = false;
                    });
                }
            }
        } else {
            task.value.areaList.forEach(item => {
                item.maintainer = userStore.name;
                item.maintainTime = task.value.maintainTime;
                item.taskNum = task.value.taskNum;
                item.maintainerId = getUserId();
                item.divisionFlag = item.area ? '0' : '1';
            })
            saveEmergencyDisposal(task.value.areaList).then(response => {
                // localStorage.setItem(task.value.id+'应急处置对策', task.value.areaList[0].area?'0':'1')
                proxy.$modal.msgSuccess("保存成功");
                openEmergencyDisposal.value = false;
            });
        }
    });
}

// 错误校验出现的次数
function most(arrays) {
	console.log(arrays)
    let newObj = {};
    for (let i = 0; i < arrays.length; i++) {
        let val = arrays[i].substring(0, arrays[i].lastIndexOf('.'));
        newObj[val] === undefined ? newObj[val] = 1 : newObj[val]++;
    }
    return newObj;
}

// 返回报错信息提示
function errorMessage(newObj, name, num, refName) {
	console.log(newObj)
    const arr = [];
    const clearRules = [];
    for (const val in newObj) {
        if (newObj[val] == num) {
            if (name == 'area') {
                arr.push(form.value.areaList[val.split('.')[1]].area + '所在地区未填写完整')
            } else {
                arr.push(form.value.areaList[val.split('.')[1]].city + '所在地区未填写完整')
            }
        } else {
            clearRules.push(val.split('.')[1])
        }
    }
    clearRuless(clearRules, refName);
    return arr
}

// 清楚错误校验信息
function clearRuless(arr, refName) {
    const newArr = [];
    for (let i = 0; i < arr.length; i++) {
        newArr.push('areaList.' + arr[i] + '.buildingDamage', 'areaList.' + arr[i] + '.casualties', 'areaList.' + arr[i] + '.geologicHazard', 'areaList.' + arr[i] + '.secondaryDisaster', 'areaList.' + arr[i] + '.earthquakeTraffic', 'areaList.' + arr[i] + '.otherDisaster')
    }
    newArr.forEach(item => {
        if (refName == 1) {
            proxy.$refs['disasters'].getDisasterScenariosRef().clearValidate(item)
        } else if (refName == 2) {
            proxy.$refs['agels'].getAgelRef().clearValidate(item)
        } else if (refName == 3) {
            proxy.$refs['emergencyDisasters'].getEmergencyDisasterRef().clearValidate(item)
        }else if (refName == 4) {
            proxy.$refs['emergencyDisposals'].getEmergencyDisposalRef().clearValidate(item)
        }
    })
}


// 预评估报告下载
function downloadReport(id,type){
    console.log(id,type)
}

/** 提交按钮 */
function submitForms() {
    proxy.$refs["historyAssessDataRef"].validate(valid => {
        if (valid) {
            if (title.value != '添加历史预评估数据') {
                updateDifference(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    openDetail.value = false;
                    getList();
                });
            } else {
                addEarthquakeDisaster(form.value).then(response => {
                    proxy.$modal.msgSuccess("保存成功");
                    openDetail.value = false;
                    getList();
                });
            }
        }
    });
}

/** 取消按钮 */
function cancel() {
    openDetail.value = false;
    reset();
}

// 模板下载
function importTemplate(name) {
    proxy.download("/base/product/downloadExcel", {
        fileName: name
    }, name);
};

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
};

/** 导出按钮操作 */
function handleExport() {
    proxy.download('/baseData/hisPr/exportExcel2', {
     ...queryParams.value  
    }, `历史预评估数据.xls`)
}

// 获取当前登录人角色
function getNowRole(){
    getRole().then(res=>{
        isAdmin.value = res.data
    })
}

//获取当前日期，格式YYYY-MM-DD
function getNowFormatDay(nowDate) {
    var char = "-";
    if (nowDate == null) {
        nowDate = new Date();
    }
    var day = nowDate.getDate();
    var month = nowDate.getMonth() + 1;//注意月份需要+1
    var year = nowDate.getFullYear();
    //补全0，并拼接
    return year + char + completeDate(month) + char + completeDate(day);
}
//获取当前时间，格式YYYY-MM-DD HH:mm:ss
function getNowFormatTime() {
    var nowDate = new Date();
    var colon = ":";
    var h = nowDate.getHours();
    var m = nowDate.getMinutes();
    var s = nowDate.getSeconds();
    //补全0，并拼接
    return getNowFormatDay(nowDate) + " " + completeDate(h) + colon + completeDate(m) + colon + completeDate(s);
}
//补全0
function completeDate(value) {
    return value < 10 ? "0" + value : value;
}

getNowRole();
getList();

</script>
  
<style lang="scss" scoped>
h3 {
    color: #333;
    height: 21px;
    font-size: 14px;
    line-height: 21px;
    display: flex;
    align-items: center;
    font-weight: bold;

    span {
        margin-right: 12px;
        display: inline-block;
        width: 3px;
        height: 14px;
        background: #333;
    }
}

.tableDialog{
    width: 1160px;
    border-collapse: collapse;
    border: 1px solid #e5ebf7;
    margin-bottom: 20px;
    .tableHead{
        background: #f5f9fe;
        td{
            padding: 5px 0px;
        }
    }
    td{
        border: 1px solid #e5ebf7;
        text-align: center;
        :deep(.el-form-item__content){
            flex-wrap: nowrap!important;
            .el-input-number{
                width: 75px!important;
            }
        }
    }
    .el-button--default{
        border: none !important;
    }
}
.preEvaReport{
    .el-row{
        border-top: 1px solid #e5ebf7;
        border-right: 1px solid #e5ebf7;
        &:last-child {
            border-bottom: 1px solid #e5ebf7;
        }

        .el-col{
            height: 34px;
            line-height: 34px;
            padding: 0 11px;
        }
        .evaTitle{
            text-align: center;
            background: #f5f9fe;
            border-left: 1px solid #e5ebf7;
            border-right: 1px solid #e5ebf7;
        }
        .el-button--default{
            border: none !important;
        }
    }
}

</style>